package sicnu.cs.ich.token.security.util;


import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.descriptor.web.ContextHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sicnu.cs.ich.token.security.config.TokenSecurity;
import sicnu.cs.ich.token.security.filter.TokenFilter;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Set;

/**
 * @author CaiKe
 */
@Component
@RequiredArgsConstructor
public class SecurityUtil {

    private final TokenSecurity tokenSecurity;
    private final TokenFilter filter;

    public static HttpServletRequest getCurrentRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    private void ensureParsed() {
        if (tokenSecurity.isTriedParseToken()) return;
        filter.lazyParseToken(getCurrentRequest());
    }

    public Set<String> getCurrentUserAuth() {
        ensureParsed();
        return tokenSecurity.getAuthorities();
    }

    public Integer getCurrentUserId() {
        ensureParsed();
        return tokenSecurity.isCredible() ? (Integer) tokenSecurity.getPrinciple() : -1;
    }

    public boolean currentUserContainsAuth(String auth) {
        ensureParsed();
        return getCurrentUserAuth().contains(auth);
    }

}

